package com.dragonsky.shop.product.service.impl;

import com.dragonsky.shop.common.utils.AjaxResult;
import com.dragonsky.shop.product.config.ProductNaCosConfig;
import com.dragonsky.shop.product.domain.vo.ProductNaCosVo;
import com.dragonsky.shop.product.entity.Product;
import com.dragonsky.shop.product.mapper.ProductMapper;
import com.dragonsky.shop.product.service.ProductService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Random;

/**
 * <p>
 * 产品表 服务实现类
 * </p>
 *
 * @author dragon
 * @since 2025-03-22 00:16:00
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    @Resource
    private ProductNaCosConfig productNaCosConfig;

    @Resource
    private ProductMapper productMapper;


    @Override
    public AjaxResult<ProductNaCosVo> getNaCosConfig() {
        return AjaxResult.succeedWith(ProductNaCosVo
            .builder()
            .productName(productNaCosConfig.getProductName())
            .productPrice(productNaCosConfig.getProductPrice())
            .productNum(productNaCosConfig.getProductNum())
            .build()
        );
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public AjaxResult<Void> seata() {
        productMapper.insert(Product
            .builder()
                .productName("seata")
                .productPrice(BigDecimal.ZERO)
                .status(Byte.parseByte("0"))
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
            .build()
        );

        Random random = new Random();
        int i2 = random.nextInt(10) + 1;
        if (i2 > 5) {
            throw new RuntimeException("产品数据需要回滚");
        }

        return AjaxResult.succeed();
    }

}
